package com.leetcode.array;

/**
 * Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, 
with the first five elements of nums being 1, 1, 2, 2 and 3.
 It doesn't matter what you leave beyond the new length.
 * @author Adiy
 *
 */
public class RemoveDuplicatesSortedArrayII {

	public static void main(String[] args) {
		int[] nums = { 1, 1, 1, 2, 2, 4, 5 };
		int len = removeDuplicates(nums);
		System.out.println();
		System.out.println(len);
	}

	public static int removeDuplicates(int[] nums) {
		int i = 0, j = 1;
		int len = nums.length;
		while (j < len - 1) {
			if (nums[i] != nums[j]) {
				i++;
				j++;
			} else {
				if (nums[j] != nums[j + 1]) {
					i += 2;
					j += 2;
				} else {
					int k = j;
					while (k < len - 1) {
						nums[k] = nums[k + 1];
						k++;
					}
					len--;
				}
			}
		}

		for (int n = 0; n < len; n++) {
			System.out.print(nums[n] + " ");
		}
		return len;
	}
}
